var CallBackList = []

/**
	@brief Set innerHTML of element
	@param ID of element
	@param Inner HTML to set
**/
function SetInnerHTML(ElementID, HTML) {
	var Element = document.getElementById(ElementID)
	var UserAgent = navigator.userAgent.toLowerCase();
	if(UserAgent.indexOf('msie') >= 0 && UserAgent.indexOf('opera') < 0) {
		HTML = '<div style="display:none">for IE</div>' + HTML
		HTML = HTML.replace(/<script([^>]*)>/gi,'<script$1 defer>');
		
		Element.innerHTML = HTML;
		Element.removeChild(Element.firstChild);
	} else {
		var Next = Element.nextSibling;
		var Parent = Element.parentNode;
		Parent.removeChild(Element);
		Element.innerHTML = HTML;
		if(Next) {
			Parent.insertBefore(Element, Next);
		} else {
			Parent.appendChild(Element);
		}
	}
}	

/**
	@brief Get checked radio's value
	@param Name of radio
	@return Value of checked radio. If there is no checked radio, return null
**/
function GetCheckedRadioValue(Name) {
	var Radios = document.getElementsByName(Name);
	var i;
	for(i = 0; i < Radios.length; ++i) {
		if(Radios[i].checked) {
			return Radios[i].value;
		}
	}
	return null;
}

/**
	@brief Replace a node's inner
	@param The id of node to replace inner
	@param The content for place in inner
**/
function Replace(ID, Content) {
	SetInnerHTML(ID, Content);
	//document.getElementById(ID).innerHTML = Content
}

/**
	@brief Insert node in front of node
	@param The id to insert in fornt
	@param Content of new node
**/
function Insert(ID, Content) {
  	var NewDiv = document.createElement("span");
  	NewDiv.innerHTML = Content;
	var Parent = document.getElementById(ID).parentNode;
  	Parent.insertBefore(NewDiv, document.getElementById(ID));
}

/**
	@brief Append a node into back 
	@param 'id': The id to append
	@param 'content': Content of new node
**/
function Append(Kwargs) {
	var ID =  Kwargs['id'];
	var Content = Kwargs['content'];
  	var NewDiv = document.createElement("span");
  	NewDiv.innerHTML = Content;
	alert(Content);
	var Element = document.getElementById(ID);
  	Element.appendChild(NewDiv);
}

/**
	@brief Edit form call back
**/
function EditForm(Kwargs) {
	var Args =  Kwargs['args'];
	var Content = Kwargs['content'];
  	Replace('content' + Args['id'], Content);
}

/**
	@brief Delete call back
**/
function Delete(Kwargs) {
	var Args =  Kwargs['args'];
  	Replace('node' + Args['id'], '');
}

/**
	@brief Replace content call back
**/
function ReplaceCallBack(Kwargs) {
	var Args =  Kwargs['args'];
	var Content = Kwargs['content']; 
  	Replace(Args['tocallback_prefix'] + Args['id'], Content);
}

/**
	@brief Insert form call back
**/
function InsertFormCallBack(Kwargs) {
	var Args =  Kwargs['args'];
	var Content = Kwargs['content']; 
	if(Args['push_back'] == '0') {
		Replace('insertform' + Args['id'], Content);
	} else {
		Replace('pushbackform' + Args['id'], Content);
	}
}

/**
	@brief Insert call back
**/
function InsertCallBack(Kwargs) {
	var Args =  Kwargs['args'];
	var Content = Kwargs['content']; 
	if(Args['push_back'] == '0') {
	  	Insert('node' + Args['id'], Content);
		Replace('insertform' + Args['id'], '');
	} else {
	  	Insert('pushbackform' + Args['id'], Content);
		Replace('pushbackform' + Args['id'], '');

	}
}

/**
	@brief Move call back
**/
function MoveCallBack(Kwargs) {
	var Args =  Kwargs['args'];
	var Content = Kwargs['content']; 
	var Element = document.getElementById('node' + Args['id']);
	var Parent = Element.parentNode;
	Parent.removeChild(Element);
	if(Args['push_back'] == '0') {
		Insert('node' + Args['to'], Content);
	} else {
		Insert('pushbackform' + Args['to'], Content);
	}
}

/**
	@brief Copy call back
**/
function CopyCallBack(Kwargs) {
	var Args =  Kwargs['args'];
	var Content = Kwargs['content']; 
	if(Args['push_back'] == '0') {
		Insert('node' + Args['to'], Content);
	} else {
		Insert('pushbackform' + Args['to'], Content);
	}
}

/**
	@brief Modify title call back
**/
function ModifyTitleCallBack(Kwargs) {
	var Args =  Kwargs['args'];
	var Title = Kwargs['title']; 
	Replace('article_title', Title);
}

/// Map for command from server
CommandMap = {	'editform': ReplaceCallBack,
				'cancel': ReplaceCallBack,
				'insertform': InsertFormCallBack,
				'modify': ReplaceCallBack,
				'insert': InsertCallBack,
				'move': MoveCallBack,
				'copy': CopyCallBack,
				'delete': Delete,
				'modify_title': ModifyTitleCallBack
			}

/**
	@brief Call for handle command
**/
function HandleCommandCallBack(Result) {
/*
	if(Result instanceof XMLHttpRequest) {
		alert(Result.responseText);
		Result = evalJSONRequest(Result.responseText);
		alert(Result);
	}*/
	var Command = Result['command'];
	var CommandArgs = Result['command_args'];
	var CommandFunction = CommandMap[Command];
	if(CommandFunction) {
		CommandFunction(CommandArgs);
	} else {
		alert('There is no such command : ' + Comand);
	}
	return Result;
}
function ShowError(Error) {
	alert(Error.message);
	alert("The metadata for MochiKit.Async could not be fetched :" + Error.number);
	return Error;
}

/**
	@breif Load command from server
	@param Command to load
	@param Args to send
**/
function LoadCommandResult(Command, Args) {
	Args['article_id'] = article_id;
	var Doc = loadJSONDoc(Path + Command, Args);

	Doc.addCallbacks(HandleCommandCallBack, ShowError);
}

/**
	@breif Load command from server with post method
	@param Command to load
	@param Args to send
**/
function LoadCommandResultWithPost(Command, Args) {
	Args['article_id'] = article_id;
	var Doc = doXHR(Path + Command, 
    {
      method: 'POST',
      sendContent: queryString(Args),
      headers: {"Content-Type":"application/x-www-form-urlencoded"} 
    });

	Doc.addCallbacks(evalJSONRequest);
	Doc.addCallbacks(HandleCommandCallBack, ShowError);
}

/**
	@brief Delete widget confirm
	@param ID of widget
**/
function DeleteConfirm(ID) {
	if(confirm('Are you sure to delete.') == true) {
		LoadCommandResult('delete', {'id': ID});
	}
}